using MediatR;
using RBAC.Domain.SmartHealthcare.Hosiptial;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using SmartHealthcare.Write.Api.Application.Command.Medicine;

namespace SmartHealthcare.Write.Api.Application.Handler.Medicine
{
    public class DeleteMedicineHandler : IRequestHandler<DeleteMedicineCommand, APIResult<bool>>
    {
        private readonly IBaseRepository<MedicineModel> medicineRepository;
        private readonly ILogger<DeleteMedicineHandler> logger;

        public DeleteMedicineHandler(IBaseRepository<MedicineModel> medicineRepository,
            ILogger<DeleteMedicineHandler> logger)
        {
            this.medicineRepository = medicineRepository;
            this.logger = logger;
        }

        public async Task<APIResult<bool>> Handle(DeleteMedicineCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<bool>();
            try
            {
                var medicine = medicineRepository.GetModel(request.Id);
                if (medicine == null || medicine.IsDeleted)
                {
                    result.Code = APIEnums.Error;
                    result.Msg = "药品不存在或已被删除";
                    result.Data = false;
                    return result;
                }

                // 逻辑删除
                medicine.IsDeleted = true;
                medicineRepository.Update(medicine);

                result.Code = APIEnums.Success;
                result.Msg = "药品出库成功";
                result.Data = true;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "药品出库失败");
                result.Code = APIEnums.Error;
                result.Msg = "药品出库失败：" + ex.Message;
                result.Data = false;
            }

            return result;
        }
    }
}
